const Koa = require('koa');
const router = require("koa-router")();
const app = new Koa();
const { check, addUser, updata, del , list} = require("./service/crud");
var bodyParser = require('koa-bodyparser');
router.post("/login", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const res = await check(`SELECT * FROM sun WHERE name="${name}" AND pwd='${pwd}'`);
    console.log();
    if (res.length) {
        ctx.body = {
            code: 2,
            msg: "登录成功",
            token: name + pwd
        }
    } else {
        ctx.body = {
            code: 4,
            msg: "登录失败，用户名或密码错误",
            token: name + pwd
        }
    }

})
router.post("/register", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const user = await check(`SELECT * FROM sun WHERE name="${name}"`)
    if (!user.length > 0) {
        await addUser(`INSERT INTO sun (name,pwd) VALUES('${name}','${pwd}')`)
        ctx.body = {
            code: 2,
            msg: "注册成功",
        }
    } else {
        ctx.body = {
            code: 4,
            msg: "注册失败，用户名已存在",
        }
    }

})
router.post("/updata", async (ctx, next) => {
    const { name, oldpwd, newpwd } = ctx.request.body;
    const res = await check(`SELECT * FROM sun WHERE name="${name}" AND pwd='${oldpwd}'`);
    if (res.length > 0) {
        const aaa = await updata(`UPDATE sun SET pwd ='${newpwd}' where id=${res[0].id}`)
        console.log(aaa);
        ctx.body = {
            code: 2,
            msg: "修改成功"
        }
    } else {
        ctx.body = {
            code: 4,
            msg: "修改失败，用户名或密码错误"
        }
    }

})
router.post("/del", async (ctx, next) => {
    const { name, pwd } = ctx.request.body;
    const user = await check(`SELECT * FROM sun WHERE name="${name}" AND pwd='${pwd}'`);
    if (user.length > 0) {
        await del(`DELETE FROM sun WHERE name = '${name}' AND pwd='${pwd}'`);
        ctx.body = {
            code: 2,
            msg: "用户注销成功",
        }
    } else {
        ctx.body = {
            code: 4,
            msg: "用户或密码错误，注销失败",
        }
    }

})
router.post("/list",async (ctx,next)=>{
    const data = await list(`SELECT * FROM list`)
    if(data.length>0){
        ctx.body = {
            code: 2,
            msg: "数据请求成功",
            list:data
        }
    }else{
        ctx.body = {
            code: 4,
            msg: "数据请求失败",
            list:[]
        }
    }
})

app.use(bodyParser());
app.use(router.routes(), router.allowedMethods());
app.listen(5000);